#include <stdio.h> 
#include <unistd.h>
#include <fcntl.h>

typedef struct 
{
	int id ;
	char name[20] ;
	double salary ;
}employee ;

int search_id(const char * filename , int id)
{
	int fd = open(filename,O_RDONLY) ;
	if(fd == -1)
		perror("open") , exit(-1) ;
	employee emp ;
		
	while(read(fd , &emp , sizeof(emp)))
	{
		if(id == emp.id)
			return 1 ;
	}
	return 0 ;
	close(fd);
}

void writeemp(const char * filename)
{
	int fd = open(filename,O_CREAT | O_RDWR ,0666);
	if(fd == -1)
		perror("open") , exit(-1);	
	employee emp;
	char name[20];
	while(1)
	{
		printf("用户ID：");
		scanf("%d",&emp.id);
		scanf( "%*[^\n]");
		scanf("%*c");
		if(!search_id(filename,emp.id))
		{
			printf("用户姓名：");
			fgets(name, sizeof(name), stdin);
	        if (strlen(name) == sizeof (name) - 1 && name[sizeof(name) - 2] != '\n')
	        {
	          	scanf( "%*[^\n]");
	            scanf( "%*c");
	        }
	        strcpy(emp.name , name);
			printf("用户薪水：");
			scanf("%lf",&emp.salary);
			scanf( "%*[^\n]");
		    scanf("%*c");
		    write(fd,&emp,sizeof(emp));
		}		
		else
		{
			printf("此用户ID已存在\n");
		}
		
		printf("是否需要继续录入用户？\n");
		char c ;
		scanf("%c",&c);
		if(c == 'N' || c == 'n')
			break;
	}	
	close(fd);
}

void reademp(const char * filename)
{
	int fd = open(filename,O_RDONLY);
	if(fd == -1) 
	{
		perror("open");
		exit(-1);
	}
	employee emp;
	while(read(fd,&emp,sizeof(emp)))
	{
		printf("此用户的ID：%d\n",emp.id);
		printf("此用户的名称：%s\n",emp.name);
		printf("此用户的：%lf\n",emp.salary);		
	}
	close(fd);
}

int main()
{
	writeemp("emp1.txt");
	reademp("emp1.txt");
}
